<template>
	<view class="page-container">
		<uni-section title="编辑用户" type="line">
			<view class="example">
				<!-- 基础表单校验 -->
				<uni-forms ref="valiForm" :rules="rules" :modelValue="valiFormData" label-position="top">

					<uni-forms-item label-width="150rpx" label="手机号" required name="mobile">
						<uni-easyinput disabled v-model="valiFormData.mobile" placeholder="请输入手机号" />
					</uni-forms-item>

					<uni-forms-item label-width="150rpx" label="姓名" required name="username">
						<uni-easyinput v-model="valiFormData.username" placeholder="请输入姓名" />
					</uni-forms-item>

					<uni-forms-item label-width="150rpx" label="短码" name="short">
						<uni-easyinput v-model="valiFormData.short" placeholder="请输入短码" />
					</uni-forms-item>

					<uni-forms-item label-width="150rpx" label="座机" name="telphone">
						<uni-easyinput v-model="valiFormData.telphone" placeholder="请输入座机" />
					</uni-forms-item>

					<uni-forms-item label-width="150rpx" label="部门" required name="d_ids">
						<uni-data-select placeholder="请选择" :localdata="d_ids" v-model="dvalue" @change="d_change" />
					</uni-forms-item>

					<uni-forms-item label-width="150rpx" label="职务" required name="j_ids">
						<uni-data-select placeholder="请选择" :localdata="j_ids" v-model="jvalue" @change="j_change" />
					</uni-forms-item>
					<uni-forms-item label-width="150rpx" label="权限" required name="role">
						<uni-data-select placeholder="请选择" :localdata="role" v-model="rvalue" @change="r_change" />
					</uni-forms-item>

					<uni-forms-item label-width="150rpx" label="备注" name="comment">
						<!-- 修改为textarea类型，实现多行输入 -->
						<uni-easyinput type="textarea" autoHeight v-model="valiFormData.comment"
							placeholder="请输入备注内容" />
					</uni-forms-item>

					<uni-forms-item label-width="150rpx" label="状态" name="status">
						<!-- 为switch组件添加颜色以匹配主题 -->
						<view class="switch-container">
							<text class="text">禁用</text>
							<switch class="switch" :checked="switchflag" @change="s_change" color="#0069cc" /><text
								class="text">启用</text>
						</view>
					</uni-forms-item>

				</uni-forms>

				<button class="submit-btn" @click="submit('valiForm')">提交修改</button>
			</view>
		</uni-section>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				_id: '',
				dvalue: null,
				jvalue: null,
				rvalue: null,
				switchflag: true,
				d_ids: [],
				j_ids: [],
				role: [],
				valiFormData: {
					mobile: '',
					username: '',
					comment: '',
					short: '',
					telphone: '',
					d_ids: [],
					j_ids: [],
					status: 0,
					// password: '111111',
					role: {

					},
					register_date: uni.$dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
				},
				rules: {
					username: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空'
						}, {
							minLength: 2,
							errorMessage: '姓名必须2个字以上'
						}, ]
					},
					d_ids: {
						rules: [{
							required: true,
							errorMessage: '请选择一个选项'
						}]
					},
					j_ids: {
						rules: [{
							required: true,
							errorMessage: '请选择一个选项'
						}]
					}
				},
			}
		},
		mounted() {
			// // //console.log('uni.$router.params', uni.$router.params)
			// this._id = e._id
			this._id = uni.$router.params._id
			this.getdep()
			this.getjob()
			this.getrole()
			this.getuser(uni.$router.params._id).then(res => {
				this.dvalue = this.valiFormData.d_ids.value
				this.jvalue = this.valiFormData.j_ids.value
				this.rvalue = this.valiFormData.role.value
				// // //console.log(this.jvalue, this.jvalue, "11111")
			})

		},
		methods: {
			async getuser() {
				const obj = uniCloud.importObject('users')
				const res = await obj.getUserInfobyId({
					_id: this._id
				}).then(res => {
					if (res.code == 0) {
						this.dataforeach(this.valiFormData, res.data)

						// // //console.log('geetuser over')
					} else {
						uni.showToast({
							title: '数据异常',
							icon: 'error'
						})
					}
				})
			},
			dataforeach(data, res) {
				// // //console.log(res, "res")
				Object.keys(data).forEach(key => {

					if (res[key]) {
						this.valiFormData[key] = res[key] || ''
					}
				})
				this.initswitchflag()
				// // //console.log(this.valiFormData)
			},
			initswitchflag() {
				if (this.valiFormData.status === 0) {
					this.switchflag = true
				} else {
					this.switchflag = false
				}
			},
			async getdep() {
				const obj = uniCloud.importObject('basedata')
				const res = await obj.getdepselect({
					data: {},
					field: {
						name: true,
						sort: true
					}
				});
				if (res.code === 0) {
					this.d_ids = res.data.map(item => ({
						value: item._id,
						text: item.name,
						sort: item.sort
					}));
				} else {
					uni.showToast({
						title: '部门数据异常',
						icon: 'none'
					});
				}
				// // //console.log(this.d_ids, 'd_ids')
			},
			async getjob() {
				const obj = uniCloud.importObject('basedata')
				const res = await obj.getjobselect({
					data: {},
					field: {
						name: true,
						sort: true
					}
				});
				if (res.code === 0) {
					this.j_ids = res.data.map(item => ({
						value: item._id,
						text: item.name,
						sort: item.sort
					}));
				} else {
					uni.showToast({
						title: '职务数据异常',
						icon: 'none'
					});
				}
				// // //console.log(this.j_ids, 'j_ids')
			},
			async getrole() {
				const obj = uniCloud.importObject('basedata')
				const res = await obj.getroleselect({
					data: {},
					field: {
						role_id: true,
						role_name: true
					}
				});
				if (res.code === 0) {
					this.role = res.data.map(item => ({
						value: item.role_id,
						text: item.role_name
					}));
				} else {
					uni.showToast({
						title: '权限数据异常',
						icon: 'none'
					});
				}
				// // //console.log(this.j_ids, 'j_ids')
			},
			d_change(e) {
				//console.log('选择的值：', e);

				if (e && e.value) {
					this.dvalue = e.value
					this.valiFormData.d_ids = e
					// console.log('d_ids的值：', this.valiFormData.d_ids);
				} else {
					this.dvalue = null
					this.valiFormData.d_ids = null
				}

			},
			j_change(e) {
				//console.log('选择的值：', e);
				if (e && e.value) {
					this.jvalue = e.value
					this.valiFormData.j_ids = e
					//console.log('jvalue的值：', this.jvalue);
				} else {
					this.jvalue = null
					this.valiFormData.j_ids = null
				}
			},
			r_change(e) {
				//console.log('选择的值：', e);
				// 检查e存在并且e.value不是undefined且不是null
				if (e && e.value !== undefined && e.value !== null) {
					this.rvalue = e.value;
					this.valiFormData.role = e;
					//console.log('rvalue的值：', this.rvalue);
				} else {
					this.rvalue = null;
					this.valiFormData.role = null;
				}
			},
			s_change(e) {
				this.switchflag = e.detail.value
				this.valiFormData.status = e.detail.value ? 0 : 1
			},
			submit(ref) {
				this.$refs[ref].validate().then(res => {
					this.valiFormData.register_date = uni.$dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
					// // // //console.log('验证通过11', res);
					this.valiFormData.mobile = Number(this.valiFormData.mobile)
					this.valiFormData.short = Number(this.valiFormData.short)
					this.valiFormData.telphone = Number(this.valiFormData.telphone)
					// // // //console.log(this.valiFormData)
					const obj = uniCloud.importObject('users')
					let event = {
						_id: this._id,
						data: this.valiFormData
					}
					const d = obj.updateUserInfo(event).then(res => {
						// 更新本地缓存 start
						// const cachedUserInfo = uni.getStorageSync('userInfo') || {};
						// const updatedUserInfo = {
						// 	...cachedUserInfo,
						// 	...this.valiFormData,
						// 	d_ids: this.valiFormData.d_ids,
						// 	j_ids: this.valiFormData.j_ids,
						// 	role: this.valiFormData.role,
						// 	status: this.valiFormData.status
						// };
						// uni.setStorageSync('userInfo', updatedUserInfo);
						// 更新本地缓存 end
						if (res.code === 0) {
							uni.showToast({
								title: res.message,
								icon: 'success'
							})
							setTimeout(() => {
								uni.$router.to({
									url: '/pagesA/user/list',
								})
							}, 1000)
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none'
							})
						}
					})
				}).catch(err => {
					//console.error('完整验证错误信息:', err) // 打印完整的错误对象
					// 新增：检查所有字段的验证状态
					// // //console.log('当前表单数据:', JSON.stringify(this.valiFormData))
				})
			},
		}
	}
</script>

<style lang="scss">
	// 页面整体背景
	page {
		background: linear-gradient(135deg, #e6f7ff, #f0f8ff);
		min-height: 100vh;
		box-sizing: border-box;
	}

	.page-container {
		padding: 20rpx;
	}

	// 卡片容器
	.uni-section {
		margin: 0;
		border-radius: 24rpx;
		overflow: hidden;
		box-shadow: 0 8rpx 24rpx rgba(0, 105, 204, 0.1);
		background: #fff;
	}

	// 卡片标题
	::v-deep .uni-section__header-title {
		font-size: 36rpx !important;
		font-weight: 600 !important;
		color: #0069cc !important;
	}

	::v-deep .uni-section__header {
		padding: 28rpx 30rpx !important;
		background: #f0f8ff !important;
		border-bottom: 1px solid #e0f0ff;
	}

	.example {
		padding: 40rpx 30rpx;
		background-color: #fff;
	}

	// 表单项
	.uni-forms-item {
		margin-bottom: 40rpx;

		// 表单标签
		::v-deep .uni-forms-item__label {
			font-size: 30rpx !important;
			font-weight: 500;
			color: #0069cc !important;
			// margin-bottom: 16rpx;
		}

		// 输入框和选择器样式
		::v-deep .uni-easyinput__content,
		::v-deep .uni-select {
			border: 1px solid #d1e9ff !important;
			border-radius: 12rpx !important;
			background: #f9fcff !important;
			transition: all 0.3s;
			// height: 80rpx;
			padding: 0 24rpx !important;
			// line-height: 80rpx;

			&:focus-within,
			&.uni-select--open {
				border-color: #0069cc !important;
				box-shadow: 0 0 0 2px rgba(0, 105, 204, 0.2);
			}

			.uni-input-input,
			.uni-select__input-text {
				font-size: 28rpx;
				color: #333;
			}

			.uni-input-placeholder,
			.uni-select__input-placeholder {
				color: #999 !important;
			}
		}
	}

	.switch-container {

		.switch {
			margin-left: 20rpx;
			margin-right: 20rpx;
		}

		.text {
			font-size: 28rpx;
		}
	}

	// 提交按钮
	.submit-btn {
		background: linear-gradient(135deg, #0081ff, #0069cc);
		border: none;
		border-radius: 50rpx;
		height: 88rpx;
		font-size: 32rpx;
		font-weight: 500;
		color: #fff;
		margin-top: 40rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 105, 204, 0.3);
		transition: all 0.3s;

		// 移除默认按钮边框
		&::after {
			border: none;
		}

		&:active {
			transform: translateY(4rpx);
			box-shadow: 0 4rpx 12rpx rgba(0, 105, 204, 0.3);
		}
	}
</style>